// @ 516
// _(:з」∠)_
"use strict";

(function() {

    // 初始化顶部时间
    let head_time = document.querySelector(".head_time"),
        changeTime = setInterval( function() {
            head_time.textContent = getCurrentTime();
        }, 1000);

    // 初始化中间列表项
    let item_view = ``,
        main_list_ul = document.querySelector(".main_list .list_ul"),
        list_item = [
            { name: "粮食", value: "food" }, { name: "水果", value: "fruit" },
            { name: "茶叶", value: "tea" }, { name: "蔬菜", value: "dish" },
            { name: "畜牧", value: "live" }
        ];
    
    list_item.forEach( ( item, index ) => {
        let thisStyle = `background: url('./images/login/${ item.value }.png');
                        background-position: center;
                        background-repeat: no-repeat;
                        background-size: 40%;`
        item_view += `<li class="item_li" value="${ item.value }"><span style="${ thisStyle }"></span></li>`;
    });

    main_list_ul.insertAdjacentHTML("beforeEnd", item_view);

    main_list_ul.addEventListener( "click", function(e) {
        let item = e.target;
        if ( item.nodeName == "SPAN" ) {
            // 移除所有同级样式
            let selectItem = main_list_ul.querySelectorAll(".select");
            for ( let x = 0, len = selectItem.length; x < len; x++ ) {
                selectItem[x].classList.remove("select");
            }

            // 添加选择样式
            item.parentNode.classList.add("select");
            console.log( item.parentNode.getAttribute("value") );
        }
        e.stopPropagation();
        return false;
    }, false);
    main_list_ul.querySelectorAll("span")[0].click();

    // 登录请求
    let login_btn = document.querySelector(".login_button button");
    login_btn.addEventListener( "click", function(e) {
        hasLoginSuccess( ( status ) => {
            if ( status ) {
                window.location.href = "./index.html";
            } else {
                alert("登录失败！");
            }
        });

        e.stopPropagation();
        return false;
    }, false);


    // 判断登录条件是否完整
    function hasLoginIntegrity() {
        let info = {},
            status = false,
            typeItem = main_list_ul.querySelector(".select"),
            username = document.querySelector("input[name='username']"),
            password = document.querySelector("input[name='password']");

        if ( typeItem ) {
            info["type"] = typeItem.getAttribute("value") || "";
            if ( info.type != "" ) status = true;
        } else { status = false; }

        if ( username ) {
            info["name"] = username.value || "";
            if ( info.type != "" ) status = true;
        } else { status = false; }

        if ( password ) {
            if ( password.value != "" ) status = true;
        } else { status = false; }

        info["status"] = status;
        return info;
    }

    // 判断登录是否成功
    function hasLoginSuccess( executable ) {
        let status = false,
            integrity = hasLoginIntegrity();

        if ( integrity.status ) {

            fetch( "./js/login/T_AREA.json", {
                method: "GET"
            }).then( ( response ) => {
                if ( response.ok ) {
                    return response.json();
                } else {
                    return Promise.reject( response );
                }
            }).then( ( result) => {
                let data = result.RECORDS;
                if ( data && data.length > 0 ) {
                    for ( let x = 0, len = data.length; x < len; x++ ) {
                        if ( integrity.name == data[x].enname ) {
                            integrity["code"] = data[x].areacode;
                            integrity["cn"] = data[x].areaname;
                            localStorage.setItem( "userInfo", JSON.stringify( integrity ) );
                            status = true;
                            break; 
                        }
                    }

                    executable( status );
                } else {

                }
            }).catch( ( err ) => {
                let content = "";
                switch( err.status ) {
                    case 400:
                        content = "请求语法错误";
                        break;
                    case 403:
                        content = "服务器拒绝请求";
                        break;
                    case 404:
                        content = "服务器未找到文件";
                        break;
                    case 408:
                        content = "服务器请求等待超时";
                        break;
                    case 500:
                        content = "服务器错误，请求失败";
                        break;
                    case 503:
                        content = "服务器当前无法使用";
                        break;
                }
    
                if ( content != "" ) {
                    alert( content );
                } else {
                    if ( err.status == null ) console.log( err.stack );
                    alert("当前无数据！");
                }
            });

        } else {
            alert("登录异常，请检查是否填写有误！");
        }
    }

    // 获取当前时间
    function getCurrentTime() {
        let currentTime = new Date(),
            c_year  = currentTime.getFullYear(),
            c_month = currentTime.getMonth() + 1,
            c_date  = currentTime.getDate(),
            c_hour  = currentTime.getHours(),
            c_minute = currentTime.getMinutes(),
            c_sequence = ( c_hour > 11 ) ? "下午" : "上午",
            c_time  = c_year +"年"+ c_month +"月"+ c_date +"日 "+ c_sequence + c_hour +":"+ c_minute;
        
        return c_time;
    }

})();